import { computed, ref } from 'vue'
import { onReachBottom, onPullDownRefresh, onLoad } from '@dcloudio/uni-app'
import { hideLoading, showLoading } from '@/util/uniapp'

export default function useDataList (api, params) {
  const pageIndex = ref(0)
  const isLoad = ref(false)
  const recordCount = ref(0)
  const dataList = ref([])
  let queryParams = {
    ...params,
  }

  onLoad(() => {
    clearList()
    getDataList()
  })

  onReachBottom(() => {
    if (isAll.value) {
      return false
    }
    pageIndex.value++
    getDataList()
  })

  onPullDownRefresh(() => {
    clearList()
    getDataList()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  })

  const isAll = computed(() => {
    return dataList.value.length >= recordCount.value
  })

  const isNodata = computed(() => {
    return !dataList.value.length && isLoad.value
  })

  const clearList = () => {
    showLoading({})
    pageIndex.value = 0
    dataList.value = []

  }
  const getDataList = async () => {
    const { data: responseData } = await api({
      ...queryParams,
      pageIndex: pageIndex.value,
    })
    dataList.value = dataList.value.concat(responseData.records)
    isLoad.value = true
    recordCount.value = responseData.recordCount
    hideLoading()
  }

  const reLoadList = (params) => {
    clearList()
    queryParams = {
      ...params,
    }
    getDataList()
  }

  return {
    dataList,
    isNodata,
    isAll,
    reLoadList,
  }
}
